package com.ankie.algorithm;

import java.util.Arrays;

/**
 * @ClassName BubbleSort
 * @Author ankie
 * @Date 2020/6/11
 * @Description 冒泡排序
 */
public class BubbleSort {

    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    private static void bubbleSort(int[] arr) {
        // arr.length - 1主要是为了避免 j + 1 数组越界
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                // 相邻元素两两对比
                if (arr[j] > arr[j + 1]) {
                    swap(arr, j, j + 1);
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {3, 44, 38, 5, 47, 15, 36, 26, 66, 29, 50, 48, 27};
        System.out.println(Arrays.toString(arr));
        bubbleSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}
